package manager.cms.service.exec;

import common.SnowflakeIdWorker;
import manager.cms.dao.CmsContentCatDao;
import manager.cms.dao.CmsContentDao;
import manager.cms.service.JdExecutor;
import manager.cms.vo.CmsContentCatVO;
import manager.cms.vo.CmsContentVO;
import manager.feign.ShopIndexFloorThirdService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(value = "hotwordsExec")
public class HotwordsExecImpl implements JdExecutor {
    @Autowired
    private ShopIndexFloorThirdService shopIndexFloorThirdService;
    @Autowired
    private CmsContentCatDao cmsContentCatDao;
    @Autowired
    private CmsContentDao cmsContenDao;
    @Override
    public void execute(Map<String,Object> mapParams) {
        try {
            CmsContentCatVO cmsContentCatVO=new CmsContentCatVO();
            JSONObject jsonObject = null;
            String hotwords = shopIndexFloorThirdService.gethHotwords();
            jsonObject = new JSONObject(hotwords);
            JSONArray hotwordsData=(JSONArray)jsonObject.get("data");
            String categoryId=String.valueOf(SnowflakeIdWorker.nextId());
            cmsContentCatVO.setId(categoryId);
            cmsContentCatVO.setName("搜索框关键字信息");
            cmsContentCatDao.addCmsContentCat(cmsContentCatVO);
            List<CmsContentVO> contentVOList=new ArrayList<CmsContentVO>();
            for(int i=0;i<hotwordsData.length();i++){
                CmsContentVO cmsContentVO=new CmsContentVO();
                String id=String.valueOf(SnowflakeIdWorker.nextId());
                Object ob=hotwordsData.get(i);
                JSONObject item=null;
                if (ob instanceof JSONArray){
                    JSONArray items=(JSONArray)hotwordsData.get(i);
                    item=(JSONObject) items.get(0);
                }
                if(ob instanceof JSONObject){
                    item=(JSONObject)hotwordsData.get(i);
                }
                cmsContentVO.setId(id);
                if(item.has("n")){
                    cmsContentVO.setTitle(item.get("n").toString());
                }
                if(item.has("u")){
                    cmsContentVO.setUrl(item.get("u").toString());
                }
                cmsContentVO.setCategoryId(categoryId);
                contentVOList.add(cmsContentVO);
            }
            cmsContenDao.addCmsContentBatch(contentVOList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
